package com.liuyucheng.idea_springboot.secret.rsa;

import com.liuyucheng.idea_springboot.sm2.Util;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import java.util.Base64;

public class RSAExample {
    public static void main(String[] args) throws Exception {
        // 生成RSA密钥对
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024); // 指定密钥长度，常用的是1024或2048位
        KeyPair keyPair = keyGen.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        //展示公钥和私钥
        String pubKey = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        String priKey = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        System.out.println("pubKey = " + pubKey);
        System.out.println("pubKey2 = " + Util.byteToHex(publicKey.getEncoded()));
        System.out.println("priKey = " + priKey);
        System.out.println("priKey2 = " + Util.byteToHex(privateKey.getEncoded()));

        // 待加密的明文
        String plaintext = "Hello, this is a test message for RSA encryption.";

        // 加密
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedData = cipher.doFinal(plaintext.getBytes("UTF-8"));

        // 将加密后的数据编码为Base64字符串
        String encodedData = Base64.getEncoder().encodeToString(encryptedData);
        System.out.println("Encrypted data (Base64): " + encodedData);

        // 解密
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decodedData = Base64.getDecoder().decode(encodedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        String decryptedText = new String(decryptedData, "UTF-8");
        System.out.println("Decrypted data: " + decryptedText);
    }
}
